package com.qcby.service.impl;

import com.qcby.common.MyExam.ResData;
import com.qcby.common.MyExam.ShowByPage;
import com.qcby.dao.MyTestDao;
import com.qcby.entity.Exam;
import com.qcby.entity.Result;
import com.qcby.entity.Student;
import com.qcby.service.MyTestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class MyTestServiceImpl implements MyTestService {

    @Autowired
    MyTestDao myTestDao;

    @Override
    public Result<List<ResData>> showExamInfoByPage(ShowByPage info) {

        info.setOffset(info.getPageSize()*(info.getPage()-1));

        //首先更新当前所展示的考试的状态
        String currenttime = info.getCurrenttime();
//        System.out.println("currenttime = " + currenttime);
        // 定义时间格式（与字符串格式完全匹配）
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 将字符串解析为 LocalDateTime 对象
        LocalDateTime currentTime = LocalDateTime.parse(currenttime, formatter);
//        System.out.println("currentTime = " + currentTime);

        //获取学生id
        int sid = myTestDao.getStudentIdByName(info.getSelf()).getId();
        info.setSid(sid);


        List<ResData> examList = myTestDao.showExamInfoByPage(info);

        System.out.println("examList = " + examList.toString());



//        for (ResData exam : examList) {
//            // 如果考试持续时间为0,则考试类型为笔记自测，直接跳过，不改变考试状态
//            if(exam.getDuration() == 0){
//                continue;
//            }
//
//
//            LocalDateTime examtime = exam.getExamtime();
//            LocalDateTime endtime = examtime.plusMinutes(exam.getDuration());
////            System.out.println("examtime = " + examtime);
////            System.out.println("endtime = " + endtime);
//            if(currentTime.isBefore(examtime)){
//                // 考试状态切换为已发布
//                int count = myTestDao.updateStatusToweikaishi(exam);
//                if(count == 0){
//                    return Result.error("考试状态切换错误，请联系管理员");
//                }
//            }
//            else if(currentTime.isAfter(examtime) && currentTime.isBefore(endtime)){
//                // 考试状态切换为进行中
//                int count = myTestDao.updateStatusTojinxingzhong(exam);
//                if(count == 0){
//                    return Result.error("考试状态切换错误，请联系管理员");
//                }
//            }
//            else if(currentTime.isAfter(endtime)){
//                // 考试状态切换为已归档
//                int count = myTestDao.updateStatusToyijieshu(exam);
//                if(count == 0){
//                    return Result.error("考试状态切换错误，请联系管理员");
//                }
//            }
//        }

        if("笔记自测".equals(info.getType())){
            return Result.success(myTestDao.showExamInfoByPageFromStudentNote(info));
        }
        else if("错题生成".equals(info.getType())){
            return Result.success(myTestDao.showExamInfoByPageFromErrorCollection(info));
        }
        else if("教师发布".equals(info.getType())){
            return Result.success(myTestDao.showExamInfoByPageFromTeacher(info));
        }
        return Result.success(myTestDao.showExamInfoByPage(info));
    }

    @Override
    public Result<Integer> getExamCount(ShowByPage info) {

        info.setSid(myTestDao.getStudentIdByName(info.getSelf()).getId());

        if("笔记自测".equals(info.getType())){
            return Result.success(myTestDao.getExamCountFromStudentNote(info));
        }
        else if("教师发布".equals(info.getType())){
            return Result.success(myTestDao.getExamCountFromTeacher(info));
        }
        else if("错题生成".equals(info.getType())){
            return Result.success(myTestDao.getExamCountFromErrorCollection(info));
        }
        return Result.success(myTestDao.getExamCount(info));
    }

    @Override
    public Result<Exam> getExamIdByInfo(Exam info) {

        // 将 LocalDateTime 转为字符串（与数据库格式一致）
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String createtimeStr = info.getCreatetime().format(formatter);
        String examtimeStr = info.getExamtime().format(formatter);
//        System.out.println("name = " + info.getName());
//        System.out.println("creator = " + info.getCreator());
//        System.out.println("createtimeStr = " + createtimeStr);
//        System.out.println("examtimeStr = " + examtimeStr);

        Exam result = myTestDao.getExamIdByInfo(
                info.getName(),       // 对应@Param("name")
                info.getCreator(),    // 对应@Param("creator")
                createtimeStr,        // 对应@Param("createtime")
                examtimeStr           // 对应@Param("examtime")
        );

        System.out.println("查询结果：" + result);
        return Result.success(result);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Result<List<ResData>> getAllExamInfoByName(String name) {
        Student student = myTestDao.getStudentIdByName(name);
        if (student == null) {
            // 根据业务需求返回合适的错误结果，比如：
            return Result.error("未找到名为" + name + "的学生信息");
        }
        int sid = student.getId();
        List<ResData> eidSidList = myTestDao.getAllExamIdBySid(sid);
        System.out.println(eidSidList.toString());
        LocalDateTime now = LocalDateTime.now();
        for (ResData examInfo :
                eidSidList) {
            int eid = examInfo.getEid();
            System.out.println("eid = " + eid);
            examInfo.setEid(eid);
            ResData exam = myTestDao.getExamInfoByEid(eid);
            System.out.println(exam+"考试");
            examInfo.setCreatetime(exam.getCreatetime());
            examInfo.setName(exam.getName());
            examInfo.setExamtime(exam.getExamtime());
            examInfo.setCreator(exam.getCreator());
            examInfo.setDuration(exam.getDuration());
            examInfo.setScore(exam.getScore());
//            examInfo.setStatus(exam.getStatus());


            LocalDateTime endTime = examInfo.getExamtime().plusMinutes(examInfo.getDuration());
            if(now.isBefore(examInfo.getExamtime())){
                if("已发布".equals(examInfo.getStatus())){
                    continue;
                }
                examInfo.setStatus("已发布");
                myTestDao.updateExamStateDynamically(examInfo);
            }
            else if(now.isAfter(examInfo.getExamtime()) && now.isBefore(endTime)){
                if("进行中".equals(examInfo.getStatus())){
                    continue;
                }
                examInfo.setStatus("进行中");
                myTestDao.updateExamStateDynamically(examInfo);
            }
            else if(now.isAfter(endTime)){
                examInfo.setStatus("已存档");
                myTestDao.updateExamStateDynamically(examInfo);
            }
        }
        return Result.success(eidSidList);
    }
}
